import 'package:flutter/material.dart';
import 'package:hello_flutter/util/CacheUtils.dart';

class TestSharedPreferences extends StatefulWidget {
  @override
  _TestSharedPreferencesState createState() => _TestSharedPreferencesState();
}

class _TestSharedPreferencesState extends State<TestSharedPreferences> {
  int counter;
  String cacheString;
  int cacheInt;
  double cacheDouble;
  bool cacheBool;

  void _save() {
    setState(() {
      counter ++;
      cacheString = "保存$counter";
      cacheInt = cacheInt + counter;
      cacheDouble = cacheDouble + counter;
      cacheBool = (counter % 2 == 1);

      CacheUtils.setIntCache("counter", counter);
      CacheUtils.setStringCache("key_string", cacheString);
      CacheUtils.setIntCache("key_int", cacheInt);
      CacheUtils.setDoubleCache("key_double", cacheDouble);
      CacheUtils.setBoolCache("key_string", cacheBool);
    });
  }

  void _update() {
    setState(() {
      counter ++;
      cacheString = "修改$counter";
      cacheInt = cacheInt + counter;
      cacheDouble = cacheDouble + counter;
      cacheBool = (counter % 2 == 1);

      CacheUtils.setIntCache("counter", counter);
      CacheUtils.setStringCache("key_string", cacheString);
      CacheUtils.setIntCache("key_int", cacheInt);
      CacheUtils.setDoubleCache("key_double", cacheDouble);
      CacheUtils.setBoolCache("key_string", cacheBool);
    });
  }

  @override
  void initState() {
    super.initState();

    counter = CacheUtils.getIntCache("key_counter");
    cacheString = CacheUtils.getStringCache("key_string");
    cacheInt = CacheUtils.getIntCache("key_int");
    cacheDouble = CacheUtils.getDoubleCache("key_double");
    cacheBool = CacheUtils.getBoolCache("key_bool");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SharedPreferences测试'),
        actions: <Widget>[
          RaisedButton.icon(
            label: Text("修改"),
            icon: Icon(Icons.update),
            onPressed: _update,
          ),
          RaisedButton.icon(
            label: Text("保存"),
            icon: Icon(Icons.save_alt),
            onPressed: _save,
          ),
        ],
      ),
      body: Container(
        padding: EdgeInsets.all(32.0),
        child: Center(
          child: Column(
            children: <Widget>[
              Text("本地存储字符串内容: $cacheString"),
              Text("本地存储整数内容: $cacheInt"),
              Text("本地存储浮点数内容: $cacheDouble"),
              Text("本地存储布尔值内容: $cacheBool"),
            ],
          ),
        ),
      ),
    );
  }
}
